#总控管理接口
from fastapi import Path,HTTPException,Query,APIRouter,Depends,status,Header
from fastapi.datastructures import Default
from fastapi.param_functions import Body
from pydantic import BaseModel,Field
from starlette.types import Message
from sql.db import yhb_crud,demo_crud
from typing import List,Optional
from sql.models import Clb, Gsb
from utils.response_code import resp_200,resp_400
from children.user import SECRET_KEY,ALGORITHM,ACCESS_TOKEN_EXPIRE_DAYS,pwd_context,oauth2_scheme,validToken
from children.user import UserIn,UserOut
from utils.utils import pages


admin_router = APIRouter()

#查询用户信息，需要token
@admin_router.get("/user_list")
def read_user(yhbh:str=Query(None,max_length=4)
            ,yhxm:str=Query(None,max_length=30)
            ,czqx:str=Query(None,max_length=3)  #服务台长度为3,
            ,order_by:str=Query(None,min_length=2,max_length=10)    #格式：yhbh_asc/yhbh_desc
            ,page = Depends(pages)
            ,pay_load=Depends(validToken)):
    if not pay_load:
        return resp_400(msg='token校验失败')
    if pay_load['czqx']!='总控':
        return resp_400(msg="无权限！")
    params = {'yhbh':yhbh,'yhxm':yhxm,'czqx':czqx}
    params = UserIn(**params)
    users,total = yhb_crud.get_user_list(params.dict(exclude_none=True)
                                    ,page=page['page'],limit=page['limit'],order_by=order_by)
    users = [UserOut(**i).__dict__ for i in users]
    if not users:
        return resp_400(msg='数据为空')
    return resp_200(data={'items':users,'total':total})

#通过用户编号删除用户信息
@admin_router.post("/delete_user")
def delete_user(yhbh :str = Body(...),pay_load=Depends(validToken)):
    if not pay_load:
        return resp_400(msg='token校验失败')
    if pay_load['czqx']!='总控':
        return resp_400(msg="无权限！")
    res = yhb_crud.delete_user(yhbh) 
    return resp_200(data={'deleted':res})

#通过用户编号编辑用户信息
@admin_router.post("/update_user")
def update_user(userInfo : UserIn,pay_load=Depends(validToken)):
    if not pay_load:
        return resp_400(msg='token校验失败')
    if pay_load['czqx']!='总控':
        return resp_400(msg="无权限！")
    if userInfo.yhmm:   
        userInfo.yhmm = pwd_context.hash(userInfo.yhmm)
    res = yhb_crud.update_user(userInfo.yhbh,userInfo.dict(exclude_unset=True)) #转化为dict类型
    return resp_200(data={'updated':res})

#添加用户
@admin_router.post("/add_user")
def add_user(user:UserIn,pay_load=Depends(validToken)):
    if not pay_load:
        return resp_400(msg='token校验失败')
    if pay_load['czqx']!='总控':
        return resp_400(msg="无权限！")
    #对密码加密，hash处理
    user.yhmm = pwd_context.hash(user.yhmm)
    res = yhb_crud.add_user(user.dict())
    return resp_200(data={"added":res})

#多表連接查詢demo
@admin_router.post("/test")
def test():
    #res = demo_crud.select_real_time_sql({'bbkh':'9001001','gsbz':'具体公司'})
    res = demo_crud.select_real_time_orm({Clb.bbkh:'9001001',Gsb.gsbz:'具体公司'})
    return resp_200(data=res)


